#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice
import sys, os, thread, random

try:
    HOME = os.environ['ROBOTS']
except KeyError:
    print 'ROBOTS environment variable is not currently defined.'
    sys.exit(0)

SLICE = os.path.join(HOME, 'slice')
FILE = os.path.join(SLICE, 'Robots.ice')
Ice.loadSlice('--all -I/usr/share/slice', ['-I' + SLICE, FILE])

import Robots
import AgentI
from AgentI import *

class AgentTeamI (Robots.AgentTeam):

    def __init__ (self, team, signposts):
        self.__team = team
        # Key   ==> Object identity.
        # Value ==> Servant.
        self.__agents = {}

        self.__signposts = signposts

        self.__mutex = thread.allocate_lock()

    # Create a team of agents.
    # Return the sequence of agent proxies.
    def create (self, robots, curr):
        self.__mutex.acquire()

        prxs = []

        # Register the servants.
        try:
            for r in robots:

                #id = curr.adapter.getCommunicator().stringToIdentity(Ice.generateUUID())
                id = curr.adapter.getCommunicator().stringToIdentity(r)
                servant = AgentI(id, curr.adapter, self.__team, r, self.__signposts)
                prx = Robots.AgentPrx.uncheckedCast(curr.adapter.add(servant, id))
                prxs.append(prx)
                self.__agents[id] = servant

        except Ice.AlreadyRegisteredException:
            pass

        # Check if some agent was destroyed.
        # TODO: all in a simple loop.
        ids = []
        for id, servant in self.__agents.iteritems():
            if servant.isZombie():
                ids.append(id)
        for id in ids:
            self.__agents.pop(id)
            
        self.__mutex.release()
        return prxs

    # Get the sequence of agent proxies.
    def list (self, curr):
        self.__mutex.acquire()
        
        prxs = []

        for id in self.__agents.keys():
            prxs.append(Robots.AgentPrx.uncheckedCast(curr.adapter.createProxy(id)))

        # Check if some agent was destroyed.
        # TODO: all in a simple loop.
        ids = []
        for id, servant in self.__agents.iteritems():
            if servant.isZombie():
                ids.append(id)
        for id in ids:
            self.__agents.pop(id)
            
        self.__mutex.release()
        return prxs
